
import { Button, message, Modal, Spin, Table, Tree, } from "antd";
import React, { useEffect, useImperativeHandle, useState } from "react";
import styles from "./style.module.scss"
import {
    GerenIcon,
    GouxuanIcon,
    WenjianjiaIcon,
    CloseIcon
} from "./icon";

/**
 * 
 * @param {} param0 
 * @returns
 * @description 员工列表 
 */
const EmployeeListModal = ({ onRef, onSuccess, employes = [], defaultSelectUserCodes = [], defaultSelectGroupIds = [] }) => {
    const defaultTreeData = employes;
    const defaultTreeDataBack = [
        {
            title: "外呼团队", //取的时候取groupName
            key: "0",//确保数据全局的key是唯一
            type: "group", //增加type类型，是group还是user
            groupId: "0",//groupId放这里,
            children: [
                {
                    title: "分组1", //取的时候取groupName
                    key: "0-0",//确保数据全局的key是唯一
                    type: "group", //增加type类型，是group还是user
                    groupId: "583363400264843264",//groupId放这里
                    children: [
                        {
                            title: "张三",  //取的时候取userName
                            key: "0-0-0", //确保数据全局的key是唯一
                            type: "user", //增加type类型，是group还是user
                            userCode: "0-0-0"//userCoce放这里
                        },
                        {
                            title: "李四",
                            key: "0-0-1",
                            type: "user",
                            userCode: "0-0-1"
                        },
                    ],
                },
                {
                    title: "分组2",
                    key: "0-1",
                    type: "group",
                    groupId: "0-1",
                    children: [
                        {
                            title: "王五",
                            key: "1535",
                            type: "user",
                            userCode: "1535",

                        },
                        {
                            title: "赵六",
                            key: "1647",
                            type: "user",
                            userCode: "1647",
                        },
                    ],
                }
            ]
        },
        {
            title: "外呼团队2", //取的时候取groupName
            key: "20",//确保数据全局的key是唯一
            type: "group", //增加type类型，是group还是user
            groupId: "20",//groupId放这里,
            children: [
                {
                    title: "分组1", //取的时候取groupName
                    key: "20-0",//确保数据全局的key是唯一
                    type: "group", //增加type类型，是group还是user
                    groupId: "583363400264843264",//groupId放这里
                    children: [
                        {
                            title: "张三",  //取的时候取userName
                            key: "20-0-0", //确保数据全局的key是唯一
                            type: "user", //增加type类型，是group还是user
                            userCode: "20-0-0"//userCoce放这里
                        },
                        {
                            title: "李四",
                            key: "20-0-1",
                            type: "user",
                            userCode: "20-0-1"
                        },
                    ],
                },
                {
                    title: "分组2",
                    key: "20-1",
                    type: "group",
                    groupId: "0-1",
                    children: [
                        {
                            title: "王五",
                            key: "212535",
                            type: "user",
                            userCode: "212535",

                        },
                        {
                            title: "赵六",
                            key: "21647",
                            type: "user",
                            userCode: "21647",
                        },
                    ],
                }
            ]
        },

    ]
    //  使用树形结构展示数据
    const [selectedKeys, setSelectedKeys] = useState([]); //选中的emloyes中的每个项的id列表，默认打开也是设置它。
    const [selectedRows, setSelectedRows] = useState([]) //已选择的全部对象
    const [saveGroupIds, setSaveGroupIds] = useState([]);
    const [selectedUserNames, setSelectedUserNames] = useState([]);
    const [selectedUserIds, setSelectedUserIds] = useState([]);
    const [saveGroupNames, setSaveGroupNames] = useState([]);
    const [selectedAllNames, setSelectedAllNames] = useState([])
    const [show, setShow] = useState(false);

    const onCancel = () => {
        setSelectedAllNames([]);
        setSelectedKeys([]);
        setSaveGroupIds([]);
        setSaveGroupNames([]);
        setSelectedUserIds([]);
        setSelectedUserNames([]);
        setSelectedRows([]);
        setShow(false);
    }

    const setDefaultCheck = (list = []) => {
        console.log("要设置默认选中的数据：", list)
        const keys = [];
        const rows = [];
        const groupIds = [];
        const usernames = [];
        const userCodes = [];
        const groupnames = []

        const findKey = (tree) => {
            tree.forEach(item => {
                if (list.includes(item.userCode) || list.includes(item.groupId)) {
                    keys.push(item.key);
                    if (item.groupId) {
                        groupIds.push(item.groupId);
                        groupnames.push(item.title);
                    }
                    if (item.userCode) {
                        userCodes.push(item.userCode);
                        usernames.push(item.title);
                    }

                    rows.push(item);

                    item.children && item.children.length > 0 && findKey(item.children)
                } else {
                    item.children && item.children.length > 0 && findKey(item.children)
                }

            })
        }

        findKey(defaultTreeData)
        setSelectedKeys(keys);
        setSelectedRows(rows)
        setSaveGroupIds(groupIds)
        setSelectedUserNames(usernames)
        setSelectedUserIds(userCodes)
        setSaveGroupNames(groupnames);
        setSelectedAllNames([...usernames, ...groupnames])
    }





    /**@description 添加|修改操作 */
    const open = async ({
        record = Object,

    }) => {
        setShow(true);
        setDefaultCheck([...defaultSelectGroupIds, ...defaultSelectUserCodes])

    }





    const onOk = () => {
        //处理数据 遍历selectedRows，判断 如果有userCode ,表示是用户，否则是分组
        const data = {
            selectedAllNames,
            saveGroupIds,
            saveGroupNames,
            selectedUserIds,
            selectedUserNames,
            selectedRows
        }
        // console.log("处理后的数据：", data)
        onSuccess && onSuccess(data)
        onCancel()
    }

    // useEffect(() => {
    //     console.log("监听到需要默认勾选的参数：", defaultSelectUserCodes, defaultSelectGroupIds)
    // }, [defaultSelectUserCodes, defaultSelectGroupIds])



    useImperativeHandle(onRef, () => ({
        open: open,

    }))






    //判断传入的key是否在已经选择的数组中，在的话，返回带有勾选框的节点


    const addIconsToTreeData = (treeData) => {
        return treeData.map(item => {
            // 深拷贝当前节点，避免修改原始数据
            const newNode = { ...item };
            // newNode.title = judgmentTitle(item)

            // 判断是否有子节点且子节点数量大于0
            if (item.children && item.children.length > 0) {
                // 分组节点使用TeamOutlined图标
                newNode.icon = <WenjianjiaIcon />;
                // 递归处理子节点
                newNode.children = addIconsToTreeData(item.children);
            } else {
                // 叶子节点使用UserOutlined图标
                newNode.icon = <GerenIcon />;
            }

            //判断节点是否在selectedKyes中，在的话，返回带有勾选框的节点

            return newNode;
        });
    }





    const [treeData, setTreeData] = useState(addIconsToTreeData(defaultTreeData))


    //判断节点是否在selectedKyes中，在的话，返回带有勾选框的节点
    const judgmentTitle = (treeData) => {
        return treeData.map(item => {
            // 深拷贝当前节点，避免修改原始数据
            const newNode = { ...item };
            if (selectedKeys.includes(item.key)) {
                newNode.title = <>
                    {newNode.title}
                    <GouxuanIcon />
                </>
            } else {
                newNode.title = <>
                    {newNode.title}
                </>
            }

            // 判断是否有子节点且子节点数量大于0
            if (item.children && item.children.length > 0) {
                // 分组节点使用TeamOutlined图标
                // newNode.icon = <WenjianjiaIcon />;
                // 递归处理子节点
                newNode.children = judgmentTitle(item.children);
            } else {
                // 叶子节点使用UserOutlined图标
                // newNode.icon = <GerenIcon />;
            }


            return newNode;
        });
    }

    const addIconForRows = (list) => {
        return list.map(item => {
            return {
                ...item,
                title: item.title,
                type: item.type,
                key: item.key,
                icon: item.type && item.type === "group" ? <WenjianjiaIcon /> : <GerenIcon />
            }
        })
    }


    //根据传入的key值判断它在defaultTreeData中的tyep，返回对应的节点
    const getTreeDataObjectByKey = (key, defaultTreeData) => {
        let obj = null;
        function fun(list) {
            for (let i = 0; i < list.length; i++) {
                if (list[i].key === key) {
                    obj = list[i];
                    break;
                } else if (list[i].children && list[i].children.length > 0) {
                    fun(list[i].children)
                }
            }
        }
        fun(defaultTreeData)
        return obj;

    }


    const onSelect = (value, e) => {
        const { type, children = null, title, key, groupId, userCode } = getTreeDataObjectByKey(e.node.key, defaultTreeData);

        console.log("当前节点的类型：", type, "当前节点的标题：", title, "当前节点的key：", key)

        if (selectedKeys.includes(e.node.key)) {

            let ressult = [];
            //去除selectedRows中item的key值等于当前节点的key值
            ressult = selectedRows.filter(item => item.key !== key)
            setSelectedRows(ressult) //保存所有数据对象

            setSelectedAllNames(selectedAllNames.filter(item => item !== title)) //保存所有name
            //如果已选中，取消选中（同时取消 ids和names）
            setSelectedKeys(selectedKeys.filter(item => item !== key)) //保存所有key值
            if (type === "group") {
                setSaveGroupIds(saveGroupIds.filter(item => item !== groupId)); //保存groupId
                setSaveGroupNames(saveGroupNames.filter(item => item !== title));
            } else {
                setSelectedUserIds(selectedUserIds.filter(item => item !== userCode)) //保存userCode
                setSelectedUserNames(selectedUserNames.filter(item => item !== title));
            }
        } else {
            setSelectedRows([...selectedRows, { type, children, title, key, groupId, userCode }])
            setSelectedAllNames([...selectedAllNames, title])
            //如果未选中，选中（同时添加 ids和names）
            setSelectedKeys([...selectedKeys, key])
            if (type === "group") {
                setSaveGroupNames([...saveGroupNames, title])
                setSaveGroupIds([...saveGroupIds, groupId])

            } else {
                setSelectedUserNames([...selectedUserNames, title])
                setSelectedUserIds([...selectedUserIds, userCode])
            }
        }
    }


    const onCancelSelected = ({ key, title, userCode, type, groupId }) => {

        let ressult = [];
        //去除selectedRows中item的key值等于当前节点的key值
        ressult = selectedRows.filter(item => item.key !== key)
        setSelectedRows(ressult)

        setSelectedAllNames(selectedAllNames.filter(item => item !== title))
        //如果已选中，取消选中（同时取消 ids和names）
        setSelectedKeys(selectedKeys.filter(item => item !== key))
        if (type === "group") {
            setSaveGroupIds(saveGroupIds.filter(item => item !== groupId));
            setSaveGroupNames(saveGroupNames.filter(item => item !== title));

        } else {
            setSelectedUserIds(selectedUserIds.filter(item => item !== userCode))
            setSelectedUserNames(selectedUserNames.filter(item => item !== title));
        }
    }


    return (
        <Modal
            title="员工列表"
            width={700}
            open={show}
            centered={true}
            destroyOnClose={true}
            onCancel={onCancel}
            footer={<>
                <Button type="primary" onClick={onOk}>确定</Button>
            </>}
        >
            <div className={styles.box}>
                <div className="left container">
                    <div className="header">
                        <div className="title">成员部门列表</div>
                    </div>
                    <div className="content">

                        <Tree
                            className="tree"
                            treeData={judgmentTitle(treeData)}
                            onSelect={onSelect}
                            showIcon={true}
                            defaultSelectedKeys={selectedKeys}
                        />
                    </div>
                </div>
                <div className="right container">
                    <div className="header">
                        <div className="title">已选择的分组或成员（{selectedRows.length}）</div>
                    </div>
                    <div className="content">

                        <PannerSelectedUser onCancelSelected={onCancelSelected} list={addIconForRows(selectedRows)} />
                    </div>
                </div>
            </div>

        </Modal>
    )
}

const PannerSelectedUser = ({ list, onCancelSelected = Function }) => {


    return <>
        {
            list.map(item => {
                return <div className="selected-item">

                    <div className="name" key={item.key}>{item.icon}{item.title}</div>
                    <div className="closeBtn" onClick={() => onCancelSelected(item)}>
                        <CloseIcon />
                    </div>
                </div>
            })
        }
    </>
}
export default EmployeeListModal;